package com.example.bingobox.ui.state;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.location.Geocoder;
import android.location.Address;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bingobox.databinding.FragmentStateBinding;
import com.example.bingobox.model.State;
import com.google.gson.Gson;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.bingobox.model.State.Location;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class StateFragment extends Fragment {

    private static final int LOCATION_PERMISSION_REQUEST = 1001;

    private FragmentStateBinding binding;
    private StateAdapter adapter;
    private final Gson gson = new Gson();
    private StateViewModel stateViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                           ViewGroup container, Bundle savedInstanceState) {
        stateViewModel = new ViewModelProvider(this).get(StateViewModel.class);

        binding = FragmentStateBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        RecyclerView recyclerView = binding.recyclerState;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 使用 ViewModel 中的数据
        State state = loadState();
        if (state != null) {
            adapter = new StateAdapter(getContext(), state);
            recyclerView.setAdapter(adapter);
        }

        // 观察 ViewModel 中的数据变化
        stateViewModel.getState().observe(getViewLifecycleOwner(), newState -> {
            if (adapter == null) {
                adapter = new StateAdapter(getContext(), newState);
                recyclerView.setAdapter(adapter);
            }
        });

        // 只更新当前城市
        if (ActivityCompat.checkSelfPermission(requireContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            updateCurrentCity();
        }

        return root;
    }

    private State loadState() {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
        File stateFile = new File(dataDir, "state.json");

        if (!stateFile.exists()) {
            if (getContext() != null) {
                Toast.makeText(getContext(), 
                    "请先进入首页初始化数据", 
                    Toast.LENGTH_LONG).show();
            }
            return new State();
        }

        try (FileReader reader = new FileReader(stateFile)) {
            State state = gson.fromJson(reader, State.class);
            if (state != null) {
                state.updateState();
                saveState(state);
            }
            return state != null ? state : new State();
        } catch (IOException e) {
            e.printStackTrace();
            if (getContext() != null) {
                Toast.makeText(getContext(), 
                    "加载状态数据失败: " + e.getMessage(), 
                    Toast.LENGTH_SHORT).show();
            }
            return new State();
        }
    }

    private void saveState(State state) {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
        File stateFile = new File(dataDir, "state.json");
        
        try (FileWriter writer = new FileWriter(stateFile)) {
            gson.toJson(state, writer);
        } catch (IOException e) {
            e.printStackTrace();
            if (getContext() != null) {
                Toast.makeText(getContext(), 
                    "保存状态失败: " + e.getMessage(), 
                    Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updateCurrentCity() {
        if (ActivityCompat.checkSelfPermission(requireContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                LOCATION_PERMISSION_REQUEST
            );
            return;
        }

        try {
            AMapLocationClient.updatePrivacyShow(requireContext(), true, true);
            AMapLocationClient.updatePrivacyAgree(requireContext(), true);
            AMapLocationClient locationClient = new AMapLocationClient(requireContext());

            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setOnceLocation(true);
            locationClient.setLocationOption(option);

            locationClient.setLocationListener(aMapLocation -> {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    // 使用 Geocoder 获取城市信息
                    Geocoder geocoder = new Geocoder(requireContext(), Locale.getDefault());
                    try {
                        List<Address> addresses = geocoder.getFromLocation(
                            aMapLocation.getLatitude(),
                            aMapLocation.getLongitude(),
                            1
                        );
                        
                        if (addresses != null && !addresses.isEmpty()) {
                            Address address = addresses.get(0);
                            State state = loadState();
                            if (state != null) {
                                // 构建完整的城市名称
                                StringBuilder cityName = new StringBuilder();
                                if (address.getAdminArea() != null) {  // 省份
                                    cityName.append(address.getAdminArea());
                                }
                                if (address.getLocality() != null) {  // 城市
                                    cityName.append(address.getLocality());
                                }

                                Location location = new Location(
                                    cityName.toString(),  // 完整城市名称
                                    aMapLocation.getLatitude(),
                                    aMapLocation.getLongitude()
                                );

                                // 设置完整地址
                                location.setAddress(cityName.toString());
                                
                                // 设置当前城市，这会自动更新城市类型
                                state.setCurrentCity(location);
                                saveState(state);
                                
                                if (adapter != null) {
                                    adapter.notifyDataSetChanged();
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(requireContext(), 
                            "获取城市信息失败: " + e.getMessage(), 
                            Toast.LENGTH_SHORT).show();
                    }
                } else if (aMapLocation != null) {
                    Toast.makeText(requireContext(), 
                        "定位失败: " + aMapLocation.getErrorInfo(), 
                        Toast.LENGTH_SHORT).show();
                }
                locationClient.onDestroy();
            });

            locationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), 
                "初始化定位服务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    private void updateCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(requireContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(requireContext(), "需要位置权限", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            AMapLocationClient locationClient = new AMapLocationClient(requireContext());
            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setOnceLocation(true);
            locationClient.setLocationOption(option);

            locationClient.setLocationListener(aMapLocation -> {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    State state = loadState();
                    if (state != null) {
                        Location location = new Location(
                            aMapLocation.getCity(),
                            aMapLocation.getLatitude(),
                            aMapLocation.getLongitude()
                        );
                        
                        // 使用高德地图提供的详细地址信息
                        StringBuilder address = new StringBuilder();
                        if (aMapLocation.getProvince() != null) {
                            address.append(aMapLocation.getProvince());
                        }
                        if (aMapLocation.getCity() != null) {
                            address.append(", ").append(aMapLocation.getCity());
                        }
                        if (aMapLocation.getDistrict() != null) {
                            address.append(", ").append(aMapLocation.getDistrict());
                        }
                        if (aMapLocation.getStreet() != null) {
                            address.append(", ").append(aMapLocation.getStreet());
                        }
                        if (aMapLocation.getStreetNum() != null) {
                            address.append(" ").append(aMapLocation.getStreetNum());
                        }
                        
                        location.setAddress(address.toString());
                        state.setCurrentLocation(location);
                        saveState(state);
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }
                    }
                } else if (aMapLocation != null) {
                    Toast.makeText(requireContext(), 
                        "定位失败: " + aMapLocation.getErrorInfo(), 
                        Toast.LENGTH_SHORT).show();
                }
                locationClient.onDestroy();
            });

            locationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), 
                "初始化定位服务失败: " + e.getMessage(), 
                Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                updateCurrentCity();
            } else {
                Toast.makeText(getContext(), "需要位置权限才能获取位置信息", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
} 